import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordSingleView } from 'vue-router'
import LayoutView from '../views/Layout.vue'
import { useMenuStore } from '@/stores/menu'

import { useAuthStore } from '@/stores/auth'
import { computed } from 'vue'
import type { RouteMenu } from '@/type/Menu'
import { routeMenuApi } from '@/api/menu'
import type { ResultData } from '@/api/service'

declare module 'vue-router' {
  interface RouteMeta {
    topButton: RouteMenu[] | null,
    rowButton: RouteMenu[] | null
  }
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: LayoutView,
      children: [
        {
          path: '/',
          name: 'home',
          component: () => import('../views/HomeView.vue')
        },
        {
          path: '/dashboard',
          name: 'dashboard',
          component: () => import('../views/dashboard/DashboardView.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    }
    // {
    //   path: '/404',
    //   name: '404',
    //   component: () => import('../views/NotFound.vue')
    // },
    // {
    //   path: '/:pathMatch(.*)*',
    //   redirect: '/404'
    // }
  ]
})

const modules = import.meta.glob('@/views/*/*.vue')
const menuMap = new Map<string, RouteMenu>()

function recurRouteMenu(routeList: RouteMenu[]) {
  routeList.forEach(it => {
    const child = it.children
    if (child.length !== 0) {
      recurRouteMenu(child)
    }
    const content = it
    // 当前菜单类型为C添加路由，并将其下子菜单中所有为F的菜单作为元数据装载
    if (content.menuType === 'C') {
      const mateData = child.filter(it => it.menuType === 'F')
      const tempRoute: RouteRecordSingleView = {
        path: content.path!,
        name: content.menuName,
        component: modules[`/src/views/${content.component}.vue`],
        meta: {
          keepAlive: true,
          topButton: mateData.filter(it => it.path === 'top'),
          rowButton: mateData.filter(it => it.path === 'row')
        },
        props: route => ({ query: route.query })
      }
      menuMap.set(content.path!!, content)
      router.addRoute('layout', tempRoute)
    }
  })
}

const authStore = useAuthStore()
const menuStore = useMenuStore()
const token = computed<string | null>(() => authStore.accessToken)
const menus = computed<RouteMenu[]>(() => menuStore.dynamic)
const whiteList = ['/login']
let initRouterFlag = false

router.beforeEach(async (to, from, next) => {
  if (token.value !== undefined && token.value !== null) {
    if (!initRouterFlag) {
      initRouterFlag = true
      if (menus.value.length == 0) {
        await routeMenuApi().then((response: ResultData<RouteMenu[]>) => {
          menuStore.setDynamic(response.data)
          recurRouteMenu(response.data)
        })
      } else {
        recurRouteMenu(menus.value)
      }
      // 使用 replace 而不是返回路径，以避免重复的历史记录
      next({ ...to, replace: true })
    } else {
      const s = menuMap.get(to.path)
      if (s !== undefined) {
        if (to.path !== '/') {
          const sp = s.component?.split('/')
          if (sp !== undefined) {
            if (sp.length === 0) {
              sp.push('')
            }
            menuStore.setTab({ innerId: s.menuId, path: to.fullPath, componentId: sp[sp.length - 1], menu: s })
          }
        }
        menuStore.setCurrentMenu(s.menuId)
        document.title = `Saber UI : ${s.menuName}`
        next()
      } else {
        menuStore.setCurrentMenu(null)
        next()
      }
    }
  } else if (!whiteList.includes(to.path)) {
    next({ path: '/login' })
  } else {
    next()
  }
})

export default router
